import plistlib
from xml.etree import ElementTree
from svgpathtools import parse_path
import numpy as np

class GlyphsGenerator:
    def __init__(self, font_info):
        self.font = {
            'appVersion': '1.0',
            'glyphs': [],
            'kerning': {},
            'metrics': [],
            'properties': [
                {'key': 'gridLength', 'integer': 1},
                {'key': 'gridSubDivision', 'integer': 1}
            ]
        }
        
    def add_glyph(self, char, svg_path):
        """将SVG路径转换为Glyphs的轮廓格式"""
        path = parse_path(svg_path)
        contours = []
        
        for segment in path:
            nodes = []
            if segment.__class__.__name__ == 'Line':
                nodes.append({'point': self._point(segment.start), 'type': 'line'})
                nodes.append({'point': self._point(segment.end), 'type': 'line'})
            elif segment.__class__.__name__ == 'CubicBezier':
                nodes.append({'point': self._point(segment.start), 'type': 'curve'})
                nodes.append({'point': self._point(segment.control1), 'type': 'offcurve'})
                nodes.append({'point': self._point(segment.control2), 'type': 'offcurve'})
                nodes.append({'point': self._point(segment.end), 'type': 'curve'})
            
            contours.append({
                'nodes': nodes,
                'closed': True
            })
        
        self.font['glyphs'].append({
            'glyphname': f'uni{ord(char):04X}',
            'layers': [{
                'layerId': 'master',
                'paths': contours,
                'width': 600  # 默认字宽
            }]
        })
    
    def _point(self, complex_num):
        return {
            'x': round(complex_num.real, 2),
            'y': round(complex_num.imag, 2)
        }
    
    def save(self, file_path):
        """生成Glyphs格式的plist文件"""
        with open(file_path, 'wb') as f:
            plistlib.dump(self.font, f)

# 使用示例
if __name__ == '__main__':
    generator = GlyphsGenerator({
        'familyName': 'NewFont',
        'unitsPerEm': 1000
    })
    
    # 添加示例字符
    generator.add_glyph('A', 'M 0 0 L 100 0 L 50 100 Z')
    generator.save('new_font.glyphs')